import requests
import re


def login():
    # 创建会话
    session = requests.session()

    # 创建请求头
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
    }

    # 获取登录页面的url
    get_login_url = 'https://github.com/login'
    # 对登陆页面发送请求
    get_login_res = session.get(get_login_url, headers=headers)
    # print(get_login_res.content.decode())
    # 获取token
    """
    为何IDE里获取的token和浏览器控制台显示的token不一样：
        因为浏览器相当于又发起了一次请求，不同的请求token都不一样
    """
    tokens = re.findall('name="authenticity_token" value="(.*?)" />', get_login_res.content.decode())

    print(tokens)

    # 获取点击登录发送请求的url
    click_login_url = 'https://github.com/session'
    # 创建请求头和请求体
    data = {
        'commit': 'Sign in',
        'authenticity_token': tokens,
        'login': 'houjiatao0527',
        'password': 'hjt920555341.',
        'trusted_device': '',
        'webauthn-support': 'supported',
        'webauthn-iuvpaa-support': 'unsupported',
        'return_to': '',
        'allow_signup': '',
        'client_id': '',
        'integration': '',
        # 'required_field_d6e2': '',  # 会改变的字段
        # 'timestamp': '1621556454962',
        # 'timestamp_secret': 'be175b6bef856e24b2954deb7af3e1990552d35ec6aba618b6c2b17526b6ee15'
    }
    # 发送请求
    click_login_res = session.post(click_login_url, data=data, headers=headers)
    print(click_login_res)

    # 获取请求个人主页的url
    profile_url = 'https://github.com/houjiatao0527'
    # 构造请求体
    # 发送请求
    response = session.get(profile_url, headers=headers)

    with open('./login_github.html', 'wb') as f:
        f.write(response.content)
    pass


if __name__ == '__main__':
    login()



